package com.bh.common.utils.file;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

import com.bh.common.utils.Base64;
import com.bh.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bh.common.config.BhtmsConfig;
import com.bh.common.constant.Constants;
import com.bh.common.utils.StringUtils;

import javax.imageio.ImageIO;

/**
 * 图片处理工具类
 *
 * @author ruo-yi
 */
public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath) {
        InputStream is = getFile(imagePath);
        try {
            return IOUtils.toByteArray(is);
        } catch (Exception e) {
            log.error("图片加载异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(String imagePath) {
        try {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        } catch (Exception e) {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url) {
        InputStream in = null;
        try {
            if (url.startsWith("http")) {
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            } else {
                // 本机地址
                String localPath = BhtmsConfig.getProfile();
                String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
                in = new FileInputStream(downloadPath);
            }
            return IOUtils.toByteArray(in);
        } catch (Exception e) {
            log.error("获取文件路径异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    public static byte[] getResourceImage(String imagePath) {
        ClassLoader classLoader = ImageUtils.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream(imagePath);
        try {
            return IOUtils.toByteArray(is);
        } catch (Exception e) {
            log.error("图片加载异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    /**
     * 文件BufferedImage类型转BASE64
     *
     * @param imagePath
     * @return
     */
    public static String imageToBase64(String imagePath) {
        //转换成字节
        byte[] bytes = getImage(imagePath);
        //转换成 base64 串
        String pngBase64 = Base64.encode(bytes).trim();
        //删除
        pngBase64 = pngBase64.replaceAll("\n", "").replaceAll("\r", "");
        return "data:image/png;base64," + pngBase64;
    }


    /**
     * 合法图片大小为2MB
     */
    private static final Long LEGAL_IMAGE_SIZE = 1024 * 2L;

    /**
     * 图片压缩 当图片大小大于2MB进行等比例压缩
     * 不修改图片尺寸进行压缩
     *
     * @param fileCO
     * @return
     */
    public static ImageInfo compressImageForScale(FileCO fileCO) throws IOException {
        byte[] imageBytes = fileCO.getFileContent();
        UUID attachmentOid = fileCO.getAttachmentOid();
        try {
            BufferedImage sourceImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
            //高度
            int height = sourceImage.getHeight();
            //宽度
            int width = sourceImage.getWidth();
            if (imageBytes.length <= 0 || imageBytes.length < LEGAL_IMAGE_SIZE * 1024) {
                return ImageInfo.builder()
                        .imageBytes(imageBytes)
                        .width(width)
                        .height(height)
                        .compressFlag(false)
                        .build();
            }
            long srcSize = imageBytes.length;
            double accuracy = getAccuracy(srcSize / 1024);

            while (imageBytes.length > LEGAL_IMAGE_SIZE * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(1f)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
                //如果压缩后图片大小未改变则跳出循环,防止死循环
                if (srcSize == imageBytes.length) {
                    log.warn("【图片压缩】msg=图片压缩失败,图片大小未改变!");
                    break;
                }
            }
            log.info("【图片压缩】附件OID={} | 图片原大小={}kb | 压缩后大小={}kb", attachmentOid, srcSize / 1024, imageBytes.length / 1024);
            return ImageInfo.builder()
                    .imageBytes(imageBytes)
                    .width(width)
                    .height(height)
                    .compressFlag(true)
                    .build();
        } catch (Exception e) {
            log.error("【图片压缩】msg=图片压缩失败!", e);
            throw e;
        }
    }

    /**
     * 计算压缩精度
     *
     * @param size
     * @return
     */
    private static double getAccuracy(long size) {
        double accuracy;
        //图片大小小于4M,压缩精度为0.44;否则精度为0.4
        if (size <= 2048 * 2) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }
}
